﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Vit.Common;
using Vit.Web.Extensions;
using Vit.Mvc.DataAnnotations;

namespace Vit.Mvc
{
    public class ViewModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            List<Attribute> attributeList = new List<Attribute>(attributes);
            DisplayColumnAttribute displayColumnAttribute = attributeList.OfType<DisplayColumnAttribute>().FirstOrDefault();
            DataAnnotationsModelMetadata result = (DataAnnotationsModelMetadata)base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            ViewModelMetadata metadata = new ViewModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute, attributes)
            {
                TemplateHint = result.TemplateHint,
                HideSurroundingHtml = result.HideSurroundingHtml,
                DataTypeName = result.DataTypeName,
                IsReadOnly = result.IsReadOnly,
                NullDisplayText = result.NullDisplayText.Locale(),
                DisplayFormatString = result.DisplayFormatString.Locale(),
                ConvertEmptyStringToNull = result.ConvertEmptyStringToNull,
                EditFormatString = result.EditFormatString.Locale(),
                DisplayName = result.DisplayName.Locale(),
                Description = result.Description.Locale(),
                ShortDisplayName = result.ShortDisplayName.Locale(),
            };

            return metadata;
        }

        public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)
        {
            if (modelType.IsGenericType)
            {
                Type genericType = modelType.GetGenericTypeDefinition();
                if (genericType.Equals(typeof(PageOfList<>)))
                {
                    modelAccessor = null;
                    modelType = modelType.GetGenericArguments()[0];
                }
            }
            return base.GetMetadataForType(modelAccessor, modelType);
        }
    }
}
